package com.ilab.util.dao;

import java.util.LinkedList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.ilab.entity.ExperNote;
import com.ilab.util.dao.sqlite.TrieiLabSQLiteOpenHelper;

public class ExperNoteDAO {
	private TrieiLabSQLiteOpenHelper dbHelper = null;
	public ExperNoteDAO(Context context){
		dbHelper = new TrieiLabSQLiteOpenHelper(context);
	}
	
	public boolean saveExperNote(ExperNote note){
		if(note!=null){
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put("exper_id", note.getExperID());
			values.put("content", note.getContent());
			values.put("create_time", note.getCreateTime());
			db.insert("exper_note", null, values);
			db.close();
			dbHelper.close();
			
			return true;
		}
		return false;
	}
	
	public PageTools<ExperNote> query(int experID,int currentPage,int pageSize){
		PageTools<ExperNote> page = new PageTools<ExperNote>(currentPage, pageSize);
		
		List<ExperNote> experInfos = null;
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		String sql = "select id,exper_id,content,create_time from exper_note where exper_id='"+experID+"' Limit "+pageSize+" Offset "+((currentPage-1)*pageSize);
		Cursor cursor = db.rawQuery(sql, null);
		if(cursor!=null){
			experInfos = new LinkedList<ExperNote>();
			int rsCount = cursor.getCount();
			for(int i=0;i<rsCount;i++){
				cursor.moveToPosition(i);
				ExperNote experNote = new ExperNote();
				experNote.setId(cursor.getInt(0));
				experNote.setExperID(cursor.getInt(1));
				experNote.setContent(cursor.getString(2));
				experNote.setCreateTime(cursor.getString(3));
				experInfos.add(experNote);
			}
		}
		cursor.close();
		db.close();
		page.setResult(experInfos);
		page.setTotalRows(this.getExperNoteCount());
		return page;
	} 
	
	public int getExperNoteCount(){
		int count = 0;
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select count(*) from exper_note", null);
		if(cursor.moveToFirst()){
			count = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return count; 
	}
	
	public void close(){
		if (dbHelper != null) {  
			dbHelper.close();  
		}  
	}

	public int deleteExperNotes(Integer[] ids) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if(ids!=null && ids.length>0){
			StringBuffer where = new StringBuffer(" id in (-1");
			for(int id:ids){
				where.append(","+id);
			}
			where.append(") ");
			return db.delete("exper_note", where.toString(), null);
		}else{
			return 0;
		}
	}
}
